package com.xjnt.base.support.admin.controller;

import java.sql.Timestamp;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.xjnt.base.support.admin.entity.Account;
import com.xjnt.base.support.admin.entity.Log;
import com.xjnt.base.support.admin.service.AccountService;
import com.xjnt.frameworks.annotation.AutoInject;
import com.xjnt.frameworks.annotation.Router;
import com.xjnt.frameworks.core.BaseController;
import com.xjnt.frameworks.web.jcaptcha.JCaptcha;
import com.xjnt.frameworks.web.message.RetMsg;
import com.xjnt.frameworks.web.render.JCaptchaRender;

@Router(name = "/login")
public class LoginController extends BaseController {

	@AutoInject
	private AccountService accountService;

	public void index() {
		render("login.html");
	}

	public void captcha() {
		render(new JCaptchaRender());
	}

	public void signin() {
		RetMsg msg = new RetMsg();
		String username = getPara("username");
		String password = getPara("password");
		// 暂时不使用
		// String accType = getPara("accType");
		/* 判断验证码 */
		String captcha = getPara("captcha");
		if (JCaptcha.hasCaptcha(getRequest(), captcha)) {
			try {
				boolean isRememberMe = false; //getParaToBoolean("isRememberMe");
				UsernamePasswordToken token = new UsernamePasswordToken(username, password, isRememberMe);
				Subject subject = SecurityUtils.getSubject();
				subject.login(token);
				if (subject.isAuthenticated()) {
					Session session = subject.getSession();
					session.setAttribute("CURR_USER", accountService.findByName(username));
				}
				msg.pushOk("登陆成功");
				writerLog("/login", "signin", username, "登录");
			} catch (AuthenticationException ex) {
				if (ex instanceof UnknownAccountException) {
					msg.pushError("用户名或密码错误!");
				}

				if (ex instanceof LockedAccountException) {
					msg.pushError("用户被锁定!");
				}

				if (ex instanceof IncorrectCredentialsException) {
					msg.pushError("用户名或密码错误!");
				}
			}
		} else {
			msg.pushError("验证码错误");
		}
		renderJson(msg);
	}
	
	public void logout(){
		Subject subject = SecurityUtils.getSubject();
		if(null != subject){
			writerLog("/login", "logout", ((Account)subject.getPrincipal()).getStr(Account.USERNAME), "注销");
			subject.logout();
		}
		redirect("/login");
	}
	
	private void writerLog(String name, String methodName, String loginName, String type){
		Log log = new Log();
		log.set(Log.NAME, name);
		log.set(Log.ACTION, methodName);
		log.set(Log.IPADDR, getRequest().getRemoteAddr());
		log.set(Log.USERNAME, loginName);
		log.set(Log.REMARK, "");
		log.set(Log.TYPE, type);
		log.set(Log.CREATETIME, new Timestamp(System.currentTimeMillis()));
		log.save();
	}
}
